
#include "qevent.h"
#include "qlogging.h"
#include "qtimer.h"
#include "CCDirector.h"
#include "CCLuaEngine.h"
#include "script_support/CCScriptSupport.h"
#include "CCLuaStack.h"
#include "CCEGLView.h"

#include "AppDelegate.h"
#include "GLWidget.h"
#include "WidgetsMenu.h"
#include "EditorScene.h"
#include "layers_scenes_transitions_nodes/CCScene.h"

USING_NS_CC;

QCGLWidget::QCGLWidget(QWidget* parent /* = nullptr */)
: QGLWidget(QGLFormat(QGL::DoubleBuffer), parent)
, _timer(nullptr)
{
    setMouseTracking(true);
}

QCGLWidget::~QCGLWidget()
{
}

void QCGLWidget::paintEvent(QPaintEvent* event)
{
    _doDraw();
}

void QCGLWidget::resizeEvent(QResizeEvent* evnet)
{
	QGLWidget::resizeEvent(evnet);

    if (_timer)//if init
    {
        int w = evnet->size().width();
        int h = evnet->size().height();
        CCEGLView::sharedOpenGLView()->setFrameSize(w, h);
        CCEGLView::sharedOpenGLView()->setDesignResolutionSize(w, h, kResolutionShowAll);

        _doDraw();
    }
}

void QCGLWidget::_doDraw()
{
    makeCurrent();
    cocos2d::CCDirector::sharedDirector()->mainLoop();
    swapBuffers();
}

void QCGLWidget::cocos2dDraw()
{
    _doDraw();
}

void QCGLWidget::createCocos()
{
	_timer = new QTimer(this);
	connect(_timer, SIGNAL(timeout()), this, SLOT(cocos2dDraw()));

	_timer->start(20);
}

void QCGLWidget::InitGL()
{
    makeCurrent();

    CCEGLView::sharedOpenGLView();//for init

    new AppDelegate;

    auto d = CCDirector::sharedDirector();
    d->setOpenGLView(CCEGLView::sharedOpenGLView());
    d->setAnimationInterval(0);
    d->setProjection(kCCDirectorProjection2D);

    createCocos();
}
